package com.shop.search.service.impl;

import com.shop.common.entity.CommonResult;
import com.shop.search.mapper.SearchProductMapper;
import com.shop.search.pojo.SearchProduct;
import com.shop.search.service.SearchProductService;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 搜索业务
 * @author ghy
 * @version 1.0
 * @date 2020-11-02
 */
@Service
public class SearchProductServiceImpl implements SearchProductService {

    @Autowired
    SearchProductMapper searchProductMapper;

    @Override
    public List<SearchProduct> findAll() {
        return searchProductMapper.findAll();
    }

    @Autowired
    SolrClient solrClient;

    /**
     * 导入数据到Solr
     *
     * @return
     */
    @Override
    public CommonResult initData() {

        /**
         * <field name="product_pname" type="text_ik" indexed="true" stored="true"/>
         * 	<field name="product_price" type="pfloat" indexed="true" stored="true"/>
         * 	<field name="product_pimage" type="text_general" indexed="false" stored="true"/>
         * 	<field name="product_pdesc" type="text_ik" indexed="true" stored="true"/>
         *
         * 	<!-- 复制域，在操作普通域时，会把普通域的值复制一份到复制域中；
         * 		在搜索时，可以通过搜索复制域找到对应的普通域[多个]进行搜索 -->
         * 	<field name="product_keyword" type="text_ik" indexed="true" stored="false" multiValued="true"/>
         *
         * 	<copyField source="product_pname" dest="product_keyword"/>
         * 	<copyField source="product_pdesc" dest="product_keyword"/>
         */

        try {
            List<SearchProduct> list = searchProductMapper.findAll();

            Collection<SolrInputDocument> docs = new ArrayList<>();
            for (SearchProduct product : list) {
                SolrInputDocument doc = new SolrInputDocument();
                doc.setField("id", product.getId().toString());
                doc.setField("product_pname", product.getPname());
                doc.setField("product_price", product.getPrice().floatValue());
                doc.setField("product_pimage", product.getPimage());
                doc.setField("product_pdesc", product.getPdesc());

                docs.add(doc);
            }

            solrClient.add(docs);
            solrClient.commit();

            return new CommonResult("导入到solr库成功");
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new CommonResult(false,"导入到solr库失败");
    }

    /**
     * 搜索
     *
     * @param keyword
     * @return
     */
    @Override
    public List<SearchProduct> search(String keyword) throws Exception {

        SolrQuery query = new SolrQuery();
        //设置查询条件
        query.setQuery(keyword);
        //分页
        query.setRows(10);
        query.setStart(0);
        //排序
        query.setSort("product_price", SolrQuery.ORDER.asc);
        //设置复制域查询
        query.set("df", "product_keyword");

        //增加高亮
        query.addHighlightField("product_pname");
        query.setHighlightSimplePre("<span style='color:red'>");
        query.setHighlightSimplePost("</span>");

        //执行搜索
        QueryResponse response = solrClient.query(query);
        SolrDocumentList results = response.getResults();
        //System.out.println(results);

        //得到高亮结果
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();



        List<SearchProduct> productList = new ArrayList<>();

        for (SolrDocument result : results) {
            String id = (String) result.getFieldValue("id");
            String product_pname = (String) result.getFieldValue("product_pname");
            Float product_price = (Float) result.getFieldValue("product_price");
            String product_pimage = (String) result.getFieldValue("product_pimage");
            String product_pdesc = (String) result.getFieldValue("product_pdesc");

            //得到高亮的记录
            Map<String, List<String>> map = highlighting.get(id);
            if(map != null) {
                //有高亮
                List<String> strings = map.get("product_pname");  //["<span style='color:red'>华为</span>NOVA15"]
                //把商品名称换成高亮的效果
                product_pname = strings.get(0); //"<span style='color:red'>华为</span>NOVA15"
            }

            SearchProduct product = new SearchProduct();
            product.setId(Long.parseLong(id));
            product.setPname(product_pname);
            product.setPrice(product_price.longValue());
            product.setPimage(product_pimage);
            product.setPdesc(product_pdesc);
            productList.add(product);

        }

        return productList;
    }
}
